<?php
namespace app\admin\controller;
use app\admin\model\User as UserModel;
use app\admin\model\Wenjuan as WenjuanModel;
use think\facade\Request;
use app\admin\traits\Result;
use think\validate;
use think\Db;
use Mpdf\Mpdf;
use app\common\service\AnswerService;
use app\common\service\PchartService;

class Wenjuan extends Common
{
    
    public function index(){
        if ($this->request->isAjax()) {
            $data = [
                'key' => $this->request->get('key', '', 'trim'),
                'limit' => $this->request->get('limit', 10, 'intval'),
            ];

            $order_name = empty($this->request->get('field')) ?'a_id':$this->request->get('field');
            $order_type = empty($this->request->get('order')) ?'desc':$this->request->get('order');
            
            $list = WenjuanModel::withSearch(['title'], ['title' => $data['key']])->order($order_name.' '.$order_type)//->order('a_id desc')
                ->paginate($data['limit'], false, ['query' => $data]);
               // dump(WenjuanModel::getlastsql());die;
            $user_date = [];
            foreach ($list as $key => $val) {
                $user_date[$key] = $val;
                //$user_date[$key]['typetitle'] = $val->typetitle;
            }
            return show($user_date, 0, '', ['count' => $list->total()]);
        }
		
		$data['starttime'] = date('Y-m-d H:i:s',strtotime('-1 month',time()));
		$data['endtime'] = date('Y-m-d H:i:s');
		//dump($data);die;
        return $this->fetch('',$data);
        
    }
    
    //有模版
    public function baogao(){

        $a_id = $this->request->param('a_id', 0, 'intval');
        if ($a_id) {

            $list = WenjuanModel::where('a_id', '=', $a_id)->find();
            if(empty($list['result_josn'])){
                $this->error('报告未生成');
			}
			$list['result_josn'] = json_decode($list['result_josn'],true);
			
			$list['score2'] = 100 - $list['score'];
			$this->assign('list', $list);
			$kechuang = json_decode($list['kechuang'],true);
			$this->assign('kechuang', $kechuang);

			$line_pic = PchartService::makeLine($list);
			$this->assign('line_pic', $line_pic);

			$pie_pic = PchartService::makepie($list);
			$this->assign('pie_pic', $pie_pic);
				
			
			
			//直接显示html项目
			//return $this->fetch('pdf');

			//生成pdf
			$mpdf = new \Mpdf\Mpdf([
				'mode' => 'utf-8',
				'format' => 'A4',
				// 'default_font_size' => 10,
				//'default_font' => 'gb',
				//'defaultCss'=>'p{line-height:4px}'
			]);
			//自动分页符
			$mpdf->autoPageBreak = true;
			//$mpdf->showImageErrors = true; //显示图片错误
			//$mpdf->SetHTMLHeader('页头');
			//$mpdf->SetHTMLFooter('页脚');
			$mpdf->SetDisplayMode('fullpage');
			$mpdf->autoScriptToLang = true; //这几个配置加上可以显示中文
			$mpdf->autoLangToFont = true;//这几个配置加上可以显示中文
			$mpdf->autoArabic = true; //这几个配置加上可以显示中文
			$mpdf->autoVietnamese =true;//这几个配置加上可以显示中文
			
			
			$html = $this->view->fetch('pdf');
			$stylesheet = file_get_contents('./css/pdf.css');
			$mpdf->curlAllowUnsafeSslRequests = true;
			$mpdf->WriteHTML($stylesheet, \Mpdf\HTMLParserMode::HEADER_CSS);
			$mpdf->WriteHTML($html, \Mpdf\HTMLParserMode::HTML_BODY);
			//$mpdf->Output($a_ids.'.pdf', 'D');
				$mpdf->Output('企业创新量化测评暨科创板、创业板上市和股权融资创新达标测评初评报告.pdf', 'D');
				

        } else {
            $this->error('参数错误');
        }
    }
    
    //没模版
    public function baogao_notpl(){

        $a_id = $this->request->param('a_id', 0, 'intval');
        if ($a_id) {

            $list = WenjuanModel::where('a_id', '=', $a_id)->find();
            if(empty($list['result_josn'])){
                $this->error('报告未生成');
            }
            $list['result_josn'] = json_decode($list['result_josn'],true);
            $kechuang = json_decode($list['kechuang'],true);
            
            $mpdf = new \Mpdf\Mpdf([
                'mode' => 'utf-8',
                'format' => 'A4',
                'default_font_size' => 10,
                'default_font' => 'gb',
                //'defaultCss'=>'p{line-height:4px}'
            ]);
            //$mpdf->autoScriptToLang = true;
            //$mpdf->autoLangToFont = true;
            //自动分页符
            $mpdf->autoPageBreak = true;
            //$mpdf->SetHTMLHeader('页头');
            //$mpdf->SetHTMLFooter('页脚');
            
            $mpdf->SetDisplayMode('fullpage');
            $mpdf->autoScriptToLang = true; //这几个配置加上可以显示中文
            $mpdf->autoLangToFont = true;//这几个配置加上可以显示中文
            $mpdf->autoArabic = true; //这几个配置加上可以显示中文
            $mpdf->autoVietnamese =true;//这几个配置加上可以显示中文


            $html = '<!DOCTYPE html>
                <html>
                <head>
                    <mate charest="utf-8" />
                </head>
                <link rel="stylesheet" href="/css/pdf.css" media="all">
                <body>
                <div class="flex">
                <div style="width:80%;">
                    <div class="industry2 flex">
                        <img class="logo" src="https://wenjuan2.haidanet.com/images/logo1.png" height=40>
                        <div class="flex-direction">
                            <span>深圳派富知识产权</span><span>投资咨询有限公司</span>
                        </div>
                        <span class="industry flex-grow">企业创新量化测评暨科创板、创业板上市和股权融资创新达标测评初评报告</span>
                    </div>
                
                <p class="industry">' . $list["company"] . '</p>
                <p class="industry2">统一信用代码：' . $list["company_code"] . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;所属领域： &nbsp;&nbsp;&nbsp;&nbsp;' . $list["company_lingyu"] . '</p>
                <p class="intro">
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;感谢信任并完成创新量化测评（创新测）暨企业融资及科创板和创业板创新达标测评。创新测是依托国际领先创新评判架构，对标科创板和创业板上市创新要求，推算出的一套科学性强、公允性高、靠谱率准的去人为影响和可量化的创新评判体系，目前已经在北上广深等政府园区、平台机构、基金银行和企业中广泛应用。 客观数据证明，科创板和创业板对申报企业的创新要求是严格的，仅仅符合科创板的证监“4+5”科创属性和创新板的三创四新创新指引，是不能完全满足在两个板块上市的创新要求的。 是否可以成功上市，还要审核申报公司在经营、财务、法律等多个方面是否达标，而本报告就是对标科创板和创业板创新要求的6个维度和22项参数，由系统自动生成的贵司创新实力现状展示和可能存在的单项短板说明，及提升管理方案。
                    <br> </p>
                 <p class="intro">    
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    本报告将从专利、技术、研发等维度评判企业的创新现状和持续创新能力，并说明各个创新单项的优势或短板及提升管理方案。 测评满分是100分，不设下限，80分说明企业在创新方面已经达到申报科创板或创业板的要求，60-70分说明可能还需要准备1-2年，50-60分2-3年，以此类推。 需要特别说明的是，创新测不是任何机构或个人的创新评判标准，而是通过数据收集、实景分析、逻辑设置，精准画像等步骤推算生成的一套细分领域参考值对比体系，它适用于评判各个发展阶段和所有科技领域，尤其是有融资需求和上市计划的创新型企业。 派富愿意根据贵司的测评得分，协助对接金融机构，早日实现资本闭环，或如果贵司不同意我们就您处的融资需求，向政府和金融机构发送以下测评结果，则请以邮件形式，予以说明，邮址 info@paif.com.
                </p>
                <table class="main_table"><tbody><tr><th>测评单项</th><th>单项结果</th> <th>改善建议</th><th>差距比例</th> </tr>';
            foreach ($list['result_josn'] as $k => $result_josn) {
                $html .= '<tr class="subtitle"><td class="row_title" colspan="5">' . $result_josn['title'] . '</td></tr>';
                foreach ($result_josn['info'] as $k => $info) {
                    $html .= '<tr><td class="row_title">' . $info[0] . '</td>
            <td>' . $info[1] . '</td>
            <td>' . $info[3] . '</td>
            <td>' . $info[2] . '</td></tr >';
                }
            }
             $html .='<tr class="subtitle"><td colspan="5">创新六维度二十二指标综合分析图</td></tr>
             <tr><td colspan="5">
                <div id="chartContainer" style="height: 300px; width: 100%;"></div>
             </td></tr>';
             $html .='<tr><td colspan="5" class="subtitle" style="text-align: left;text-indent: 20px;"><p class="intro">鉴于专利事项是上市或融资创新审核的关注点和上市或融资过程中可能遇到的最大风险点，派富已经就贵公司的专利质量、布局、保护和侵权风险等做了人工分析，可以做为“高级版测评”包括的《专利闪调报告》有偿提供， 如有需求， 请向您的派富联系人说明或邮件发送 info@paif.com.</p>
             <p class="intro">我们希望近期可以通过视频会议为您处详细解读报告内容，并根据贵司的实际情况， 提出创新提升和资本闭环的实施方案。</p>
             </td></tr>';
             
            $html .= '</tbody></table></div>
                <div style="width: 20%;background: #595959;color: #fff;">
                    <p class="industry2">' . $kechuang["result"] . '</p>
                    <p class="industry2">' . $list["summary_preview"] . '</p>
                    <table class="main_table"><tbody>
                    <tr><th colspan="5">'.$kechuang["title"].'</th></tr>';
                    foreach ($kechuang['info'] as $ke => $va) {
                         $html .= '<tr><th>'.$va['k'].'</th><th>'.$va['v'].'</th></tr>';
                    }
                    $html .= '</tbody></table>
                </div>
            </div>
            </body></html>';
            $html .= '<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script><script type="text/javascript">
window.onload = function () {
	var chart = new CanvasJS.Chart("chartContainer", {
		data: [              
			{
				type: "line",
				dataPoints:'.$list['chart1_json'].'
			},
			{
				type: "line",
				dataPoints: '.$list['chart2_json'].'
			}
		]
	});
	chart.render();
}
</script>';
           
          
           echo $html;die;
           
            $stylesheet = file_get_contents('./css/pdf.css');
            $mpdf->WriteHTML($stylesheet, \Mpdf\HTMLParserMode::HEADER_CSS);
            $mpdf->WriteHTML($html, \Mpdf\HTMLParserMode::HTML_BODY);
            $mpdf->Output($list['user_id'].'_'.$list['a_id'].'.pdf', 'D');

        } else {
            $this->error('参数错误');
        }
    }
    
    public function edit(){
       if ($this->request->isPost()) {
            $data = $this->request->post();
			
			$validate = validate('Buliao');
			if (!$validate->check($data)) {
				//令牌数据无效时重置令牌
				$validate->getError() != '令牌数据无效' ? $token = Request::token() : $token = '';
				$msg = Result::error($validate->getError(), null, ['token' => $token]);
				return $msg;
			}
				
            if ($data['a_id']) {
				$data['update_time'] = time();
                //编辑
                $res = WenjuanModel::update($data, ['a_id' => $data['a_id']]);
                if ($res) {
                    $msg = Result::success('编辑成功', url('/admin/buliao-list'));
                } else {
                    $msg = Result::error('编辑失败');
                }
            } else {
                //添加
                $WenjuanModel = new WenjuanModel;
				$data['create_time'] = time();
                $res = $WenjuanModel->allowField(true)->save($data);
                if ($res) {
                    $msg = Result::success('添加成功', url('/admin/buliao-list'));
                } else {
                    $msg = Result::error('添加失败');
                }
            }
            return $msg;
        } else { 
            $a_id = $this->request->get('a_id', 0, 'intval');
            if ($a_id) {
                $list = WenjuanModel::where('a_id', '=', $a_id)->find();
                $this->assign('list', $list);
            }
            $typelist = Db::name('type')->order('type_id asc')->column('type_id,title');
			$this->assign('typelist', $typelist);
            $levellist= Db::name('level')->order('id asc')->field('id,title')->select();
			$this->assign('levellist', $levellist);
            return $this->fetch();
        } 
        
    }
    
    
    public function del(){
        $a_id = $this->request->param('a_id', 0, 'intval');
        if ($a_id) {
                $res = WenjuanModel::where('a_id='.$a_id)->delete();
                if ($res) {
                    $msg = Result::success('删除成功');
                } else {
                    $msg = Result::error('删除失败');
                }
        
                return $msg;
            
        } else {
            $this->error('参数错误');
        }
        
    }
    
    
    //清空
	public function delall()
    {
        $res = Db::name('buliao')->delete(true);
        if ($res) {
            $msg = Result::success('操作成功');
        } else {
            $msg = Result::error('操作失败');
        }
        return $msg;
    }
    
	//全部导出
    public function daochuall()
    {
		$s_id = config('app.s_id');
		$list = AnswerService::getGuestions($s_id);


        $question_titles = [];
        $question_infos = [];
        foreach($list as $k=>$v){
            $question_titles[] = $v['title'];
            $question_infos[$v['id']] = $v;
        }
        array_unshift($question_titles,'得分');
        
		$starttime = input('starttime');
		$endtime = input('endtime');
        $wenjuanList = WenjuanModel::where('status',1)->whereTime('create_time', [$starttime,$endtime])->field('a_id,info,score')->order('a_id desc')->select();
        
		$cate_list = db('cate')->column('id,title');
		$arr = [];
        foreach($wenjuanList as $k=>$v){
            //处理每份答卷的数据。
            $info = json_decode($v['info'],true);
            $data_new = [];//处理后的新数据
            //$info = array_merge($array_info_temp,$info);
            $data_new[] = $v['score'];
			$info = !empty($info)?$info:[];
            foreach ($info as $k1=>$v1){
                $temp = explode('_',$k1);
                $q_id = $temp[0];
				if(empty($question_infos[$q_id])){
					continue;
				}
                $question_info = $question_infos[$q_id];
                if($question_info['type'] == 'YesNo'){
                    $data_new[] = ($v1 == 1)?'是':(($v1 == 2)?'否':'');
                }elseif($question_info['type'] == 'Picker'){
					if($q_id == 17){
						//$data_new[] = db('cate')->where('id',$v1)->value('title');
						$data_new[] = $cate_list[$v1];
					}else{
					  //dump($v['a_id'].'_'); dump($q_id);
						$params = json_decode($question_info['params'],true);
						$data_new[] = ($v1<1)?'':(isset($params['selector'][$v1-1])?$params['selector'][$v1-1]:'');
					}
                }else{
                    $data_new[] = $v1;//InputNumber数字填空 Input填空Textarea文本
                }
            }
            $arr[$k] = $data_new;
        }

        $config = [
            'path' => './uploads/daochu' // xlsx文件保存路径
        ];
        $excel  = new \Vtiful\Kernel\Excel($config);

        // fileName 会自动创建一个工作表，你可以自定义该工作表名称，工作表名称为可选参数
        $filePath = $excel->fileName('问卷导出_'.date('YmdH').'.xlsx', 'sheet1')
            ->header($question_titles)
            ->data($arr)
            ->output();
        return redirect('/uploads/daochu/问卷导出_'.date('YmdH').'.xlsx');
    }
}



?>